//////////////////////注册
//判断是否在微信打开
var isweixin="";
function is_weixn(){
    var ua = navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i)=="micromessenger") {
        return true;
    } else {
        return false;
    }
}
if(is_weixn()){
    isweixin="/weixin/";//原始跳转页面
}
//判断PC
var userAgentInfo = navigator.userAgent;
var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
var IsPC=true;
for (var v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) { IsPC=false; break; }
}

var clocktim=60;//读秒
var phonenumber;
var username;
var password;
var tohrefurl=isweixin+"pulu.html";//原始跳转页面
var fromuser="";
var zctype=1;//默认为普通注册
//cookie保存数据 用于登录页面
var loca=location.href;
function getFromUser(){
    if(loca.match(/fromuser=[a-z0-9]+/)){
        fromuser=loca.match(/fromuser=[a-z0-9]+/)[0].split("=")[1];
        if(!/[0-9]/.test(fromuser)){fromuser=""}
    }else{
        if($.cookie("fromuser")&&/[0-9]/.test($.cookie("fromuser"))){
            fromuser=$.cookie("fromuser");
        }
    }
}
if(/newsid=/.test(loca)){
    var newsid=loca.match(/newsid=[0-9]+/)[0];
    getFromUser();
    if(fromuser&&/[0-9]/.test(fromuser)){
        $.cookie("fromuser",fromuser);
        $.cookie("fromid",newsid);
        zctype=2;
    }
}else if(/qid=/.test(loca)){
    var qid=loca.match(/qid=[0-9]+/)[0];
    getFromUser();
    if(fromuser&&/[0-9]/.test(fromuser)){
        $.cookie("fromuser",fromuser);
        $.cookie("fromid",qid);
        zctype=2;
    }
}else if(/eid=/.test(loca)){
    var eid=loca.match(/eid=[0-9]+/)[0];
    getFromUser();
    if(fromuser&&/[0-9]/.test(fromuser)){
        $.cookie("fromuser",fromuser);
        $.cookie("fromid",eid);
        zctype=2;
    }
}
//扫码加好友
if(/index.html#fromuser=[0-9a-z]+/.test(location.href)){
    fromuser=loca.match(/fromuser=[a-z0-9]+/)[0].split("=")[1];
    if(/[0-9]/.test(fromuser)){$.cookie("fromuser",fromuser);}
}
//从登录页面过来
if(document.referrer.match(/login/)){
    $("#register").css("display","block");
    $(".pagedlist_item").css("display","none");
}else if(document.referrer.match(/weixinsharenews/)||document.referrer.match(/questiondetail/)||document.referrer.match(/shareexppage/)||document.referrer.match(/newsdetail/)||document.referrer.match(/pulunews_share/)){
    //从详情页进来快速注册
    $("#register").css("display","block");
    $(".pagedlist_item").css("display","none");
    $("#register .text_note").html("无需下载，快速注册，查看精彩内容");
}
//微信关注公众号
function focusWX(){
    phonenumber=$("#phonenumber").val();
    var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
    $.ajax({
        type:"get",
        url:harassurl+md5phonenumber,
        success:function(d){
            location.href=tohrefurl;
            // //没有关注
            // if(!d.Data){
            //     $("#harass").css("display","block");
            // }
            // //已经关注 红包图
            // else{
            //     //$("#finishnotic").css("display","block");
            //     //console.log("页面跳转1");
            //     location.href=tohrefurl;
            // }
        }
    });
}
//关闭微信关注弹框
$("#closeharass").click(function(){
    $("#harass").css("display","none");
    $("#finishnotic").css("display","block");
});
$("#closeharass1").click(function(){
    phonenumber=$("#phonenumber").val();
    var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
    $.ajax({
        type:"post",
        url:changeqrurl,
        data:{"userId":md5phonenumber},
        success:function(d){
            $("#harass").css("display","none");
            $("#finishnotic").css("display","block");
        }
    })
});
//展开注册
$("#registerbtn").click(function(){
    location.href+="#register";
    $("#register").css("display","block");
    $(".pagedlist_item").css("display","none");
});
//关闭注册
$("#registerback").click(function(){
    if(document.referrer.match(/login/)){
        history.go(-1);
    }else{
        history.go(-1);
        $("#register").css("display","none");
        $(".pagedlist_item").css("display","block");
    }
});

//验证码
var yanzhengma="yes";//验证码可以点击 控制点击一次
$("#timclock").click(function(){
    //alert("执行");
    $("#tishiinfor").html("");
    phonenumber=$("#phonenumber").val();
    username=$("#username").val();
    password=$("#password").val();
    //reg=/0?(13|14|15|18)[0-9]{9}$/;
    reg=/^\d+$/;
    if(!reg.test(phonenumber)){
        $("#tishiinfor").html("请输入正确的手机号！")
    }else if($("#username").val()===""||username.match(/\s/)){
        $("#tishiinfor").html("昵称格式有误！");
    }else if(!(/[0-9]{6,12}|[a-z]{6,12}|[A-Z]{6,12}|[0-9a-zA-Z]{6,12}/.test(password))||password.length<6||password.length>12){
        $("#tishiinfor").html("密码不符合规范！");
    }else{
        //判断是否已经存在
        var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
        if(yanzhengma==="yes"){
            yanzhengma="no";//验证码当前不能点击
            $("#timclock").html(60);
            var secondtime=setInterval(function(){
                if(clocktim>0){
                    clocktim--;
                    $("#timclock").html(clocktim);
                }else{
                    clearInterval(secondtime);
                    $("#timclock").html("获取验证码");
                    clocktim=60;
                    yanzhengma="yes";//验证码可以点击
                }
            },1000);

            //发送验证码
            $.ajax({
                type:"get",
                dataType: "json",
                url:"https://www.pulu.com/webapi/api/Sms/GetValidCode?phoneNum="+$("#phonenumber").val(),
                success:function(data){
                    console.log(data);
                    if(data.Code==="FALSE"){
                        if(data.Message.match(/a-z/)){
                            $("#tishiinfor").html("验证码获取失败，请稍后再试。");
                        }else if(data.Message.match(/5/)){
                            $("#tishiinfor").html("已经超过当天请求5次限制");
                        }
                    }else{

                    }
                }
            });

        }
    }
});
//下一步按钮
$("#nextstep").click(function(){
    //注册中包含短信验证
    $("#tishiinfor").html("");
    $("#rankErrorWord").html("");
    phonenumber=$("#phonenumber").val();
    var username=$("#username").val();
    password=$("#password").val();
    reg=/0?(13|14|15|18)[0-9]{9}$/;
    if(!/^[0-9]+$/.test(phonenumber)){
        $("#tishiinfor").html("请输入正确的手机号！")
    }
    //else if(!/^([\u4e00-\u9fa5]{1,7}|[a-zA-Z\.\s]{1,7})$/.test($("#realname").val())){
    //    $("#tishiinfor").html("姓名不符合规范！");
    //}
    //else if(!/^[\u4E00-\u9FA5a-zA-Z0-9_]{1,7}$/.test($("#username").val())){
    //    $("#tishiinfor").html("昵称仅支持中英文、数字和下划线！");
    //}
    else if(!/^([\u4e00-\u9fa5]{1,7}|[a-zA-Z\.\s]{1,7})$/.test($("#username").val())){
        $("#tishiinfor").html("姓名不符合规范！");
    }
    else if(!(/[0-9]{6,12}|[a-z]{6,12}|[A-Z]{6,12}|[0-9a-zA-Z]{6,12}/.test(password))){
        $("#tishiinfor").html("密码不符合规范！");
    }else if(/cannot/.test($("#nextstep").attr("class"))){
        $("#tishiinfor").html("您尚未选择订阅号！");
    }else if(!/[0-9]+/.test($("#phonetestinput").val())){
        $("#tishiinfor").html("请输入验证码!");
    }else{
        var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
        $.ajax({
            type:"POST",
            url:"https://www.pulu.com/webapi/api/puluuser/IsCanRegister",
            data:{
                "userId":md5phonenumber,
                "validateCode":$("#phonetestinput").val(),
                "phoneNum":phonenumber
            },
            success:function(d){
                if(d.Message=="账户已存在"){
                    $("#tishiinfor").html("该帐号已被注册！");
                }else if(d.Message=="验证码错误"){
                    $("#tishiinfor").html("验证码错误！");
                }else if(d.Message=="验证码正确"){
                    //展开排名页面
                    $("#register").css("display","none");
                    $("#ranking").css("display","block");
                }
                //console.log(d);
            }
        });
    }
});

/*展开行业*/
function showProfessionPage(){
    professionList.style.display="block";
    ranking.style.display="none";
}
/*选择展开排名*/
var choiceAdministration=false,choiceSkill=false;
function showAdministration(e){
    if(e.checked){
        administrationLi.style.display="block";
        choiceAdministration=true;
    }else{
        administrationLi.style.display="none";
        choiceAdministration=false;
    }
}
function showSkill(e){
    if(e.checked){
        skillLi.style.display="block";
        choiceSkill=true;
    }else{
        skillLi.style.display="none";
        choiceSkill=false;
    }
}
/*计算选择个数*/
var choiceProfessionNum=0;
var professionName=[];
var professionId=[];
function computeProfessiion(e){
    var labelClass= e.id.match(/\d+/)[0];
    var name=document.querySelector(".label"+ labelClass).innerHTML;
    if(e.checked){
        if(choiceProfessionNum>=3){e.checked=false;}
        else{
            choiceProfessionNum++;
            professionName.push(name);
            professionId.push(labelClass);
        }
    }else{
        choiceProfessionNum--;
        for(var i=0;i<professionName.length;i++){
            if(professionName[i]==name){
                professionName.splice(i,1);
                professionId.splice(i,1);
                break;
            }
        }
    }
    professionNum.innerHTML=choiceProfessionNum;
    var professionWord=professionName.join(",");
    document.querySelector(".professionDiv>.newsname").innerHTML=professionWord;
}
/*返回*/
function closeProfessionList(){
    professionList.style.display="none";
    ranking.style.display="block";
}
/*确认*/
function choiceOkProfessionBtn(){
    professionList.style.display="none";
    ranking.style.display="block";
}
//rankBack
$("#rankBack").click(function(){
    $("#register").css("display","block");
    $("#ranking").css("display","none");
});
//添加一个大范围
var largeNum=1;
function addLargeKeyWord(){
    $("#addLargeBtn").before('<div class="itemDiv large'+largeNum+'"> ' +
    '<div class="lf"> ' +
    '<span class="lf delBtn" onclick="delLarge('+largeNum+')">删除此项</span> ' +
    '<div style="margin-left:60px;padding-right:10px;"><input type="text" placeholder="" maxlength="7"/></div>' +
    '</div> ' +
    '<div class="lf"> ' +
    '<span class="lf">排名：</span> ' +
    '<div><select name="level"> ' +
    '<option value="4">前10%</option> ' +
    '<option value="3">前11%-30%</option> ' +
    '<option value="2">前31%-60%</option> ' +
    '<option value="1">前61%-99%</option> ' +
    '</select></div> ' +
    '</div>'+
    '</div>');
    largeNum++;
}
//添加一个小范围
var smallNum=1;
function addSmallKeyWord(){
    $("#addSmallBtn").before('<div class="itemDiv small'+smallNum+'"> ' +
    '<div class="lf"> ' +
    '<span class="lf delBtn" onclick="delSmall('+smallNum+')">删除此项</span> ' +
    '<div style="margin-left:60px;padding-right:10px;"><input type="text" placeholder="" maxlength="7"/></div> ' +
    '</div> ' +
    '<div class="lf"> ' +
    '<span class="lf">排名：</span> ' +
    '<div><select name="level"> ' +
    '<option value="4">前10%</option> ' +
    '<option value="3">前11%-30%</option> ' +
    '<option value="2">前31%-60%</option> ' +
    '<option value="1">前61%-99%</option> ' +
    '</select></div> ' +
    '</div>'+
    '</div>');
    smallNum++;
}
//删除一个大范围
function delLarge(n){$(".itemDiv.large"+n).remove();}
//删除一个小范围
function delSmall(n){$(".itemDiv.small"+n).remove();}
//验证排名信息
var TechParam=[];
function testRanking(){
    TechParam=[];
    var result=true;
    $("#rankErrorWord").html("");
    if(professionId.length==0||!$("#ranking .newsname").html()){
        $("#rankErrorWord").html("请选择公司产业方向");
        result=false;
        return result;
    }
    if(!choiceAdministration&&!choiceSkill){
        $("#rankErrorWord").html("请选择职能级别");
        result=false;
        return result;
    }
    if(choiceSkill){
        //大领域
        var largeInput=$("div[class*='large'] input");
        var largeSelect=$("div[class*='large'] select");
        var len=largeInput.length;
        var haveLarge=false;
        for(var a=0;a<len;a++){
            var thisValue=largeInput[a].value.trim();
            //console.log(thisValue);
            if(thisValue){
                haveLarge=true;
                TechParam.push({
                    "keywordType":2,
                    "techrank":largeSelect[a].value,
                    "keyWord":thisValue
                });
            }
        }
        if(!haveLarge){
            $("#rankErrorWord").html("请填写大领域关键词");
            result=false;
            return result;
        }
        else{
            var smallInput=$("div[class*='small'] input");
            var smallSelect=$("div[class*='small'] select");
            var leng=smallInput.length;
            var haveSmall=false;
            for(var b=0;b<leng;b++){
                var thisSmallValue=smallInput[b].value.trim();
                if(thisSmallValue){
                    TechParam.push({
                        "keywordType":1,
                        "techrank":smallSelect[b].value,
                        "keyWord":thisSmallValue
                    });
                    haveSmall=true;
                }
            }
            if(!haveSmall){
                result=false;
                $("#rankErrorWord").html("请填写小领域关键词");
                return result;
            }
        }
    }
    return result;
};

//最终注册
function registerFtn(){
    if(testRanking()){
        phonenumber=$("#phonenumber").val();
        var username=$("#username").val();
        password=$("#password").val();

        var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
        var md5password=hex_md5(password).substring(7, 23);
        $("#tishiinfor").html("正在注册...");
        //获取新闻类别
        var jobids=[],hobbyids=[],newsids=[];
        $(".newsname span").each(function(){
            var num=this.id.match(/[0-9]+/)[0];
            if(this.dataset.type==190){
                newsids.push(num);
            }else if(this.dataset.type==191){
                jobids.push(num);
            }else if(this.dataset.type==192){
                hobbyids.push(num);
            }
        });
        //加好友
        var fromuser="";
        var loca=location.href;
        if(loca.match(/fromuser=[a-z0-9]+/)){
            fromuser=loca.match(/fromuser=[a-z0-9]+/)[0].split("=")[1];
            if(/[0-9]/.test(fromuser)){
                zctype=2;
                $.cookie("shareUserId",fromuser);//保存回答转发者
            }
        }else if($.cookie("fromuser")&&/[0-9]/.test($.cookie("fromuser"))){
            fromuser=$.cookie("fromuser");
            zctype=2;
            $.cookie("shareUserId",fromuser);//保存回答转发者
        }
        //
        var administrationNum=0;
        choiceAdministration?administrationNum=$("#manageRank").val():'';
        var  jobId=0;
        if(choiceAdministration){ jobId=1};
        if(choiceSkill){jobId=2};
        if(choiceAdministration&&choiceSkill){ jobId=3};
        //取消加好友操作
        fromuser="";
        $.ajax({
            type:"post",
            dataType: "json",
            url:"https://www.pulu.com/webapi/api/PuluUser/Register",
            data:{
                "userId":md5phonenumber,
                "userNick":username,
                "userPhone":phonenumber,
                "password":md5password,
                "type":zctype,
                "verification_code":$("#phonetestinput").val(),
                "fromUserId":fromuser,
                "newsids":newsids,
                "jobids":jobids,
                "hobbyids":hobbyids,
                "realName":$("#realname").val(),

                "companyRank":$("#companyRank").val(),
                "manageRank":administrationNum,
                "NewJobs":professionName,
                "techKwords":TechParam,
                "jobId":jobId
            },
            success:function(data){
                //if(fromuser){console.log(fromuser);}
                //else{console.log("没有");}
                //注册成功
                if(data.Data==1){
                    //保存信息
                    $.cookie("MYID",hex_md5(phonenumber).substring(7, 23));
                    //console.log($.cookie("MYID"));
                    $.cookie("MYAVA","");
                    $.cookie("MYNICK",$("#username").val());
                    $.cookie("validateLevel",0);
                    $("#tishiinfor").html("");
                    var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
                    var md5password=hex_md5(password).substring(7, 23);
                    var username=$("#username").val();
                    //    环信创建链接
                    var conn = new WebIM.connection({
                        https: typeof WebIM.config.https === 'boolean' ? WebIM.config.https : location.protocol === 'https:',
                        url: WebIM.config.xmppURL,
                        isAutoLogin: WebIM.config.isAutoLogin,
                        isMultiLoginSessions: WebIM.config.isMultiLoginSessions
                    });
                    //注册环信
                    var options = {
                        username: md5phonenumber,
                        password: md5phonenumber,
                        nickname: username,
                        appKey: "pulu#pulu",
                        success: function (d) {
                            //console.log("成功");
                            //console.log(d)

                            //微信openid
                            if($.cookie("wxopenid")){
                                $.ajax({
                                    type:"post",
                                    url:"https://www.pulu.com/webapi/api/WebChatInfo/AddWebChatInfo",
                                    data:{"userId":md5phonenumber,"webchatId":$.cookie("wxopenid")},
                                    success:function(d){
                                        ////红包 联系人
                                        //if(!fromuser){ //联系人
                                        //    $("#register").css("display","none");
                                        //    //没有推荐人 不弹红包图 填写推荐人
                                        //    $("#fromUserPhone").css("display","block");
                                        //}else{  //红包
                                        //    //有推荐人 红包 关注判断
                                        //    if(is_weixn()){
                                        //        focusWX("finishnotic");
                                        //    }else{
                                        //        $("#finishnotic").css("display","block");
                                        //    }
                                        //}

                                        // focusWX("finishnotic");
                                        location.href=tohrefurl;
                                    }
                                })
                            }
                            else{
                                //如果是从转发页面过来的将自己的数据拼接进去
                                var loca=location.href;
                                if(/newsid=/.test(loca)){
                                    var newsid=loca.match(/newsid=[0-9]+/)[0].match(/[0-9]+/)[0];
                                    tohrefurl=isweixin+"newsdetail.html?newsid="+newsid+"#fromuser="+md5phonenumber;
                                }
                                else if(/qid=/.test(loca)){
                                    var qid=loca.match(/qid=[0-9]+/)[0].match(/[0-9]+/)[0];
                                    tohrefurl=isweixin+"questiondetail.html?qid="+qid+"#fromuser="+md5phonenumber;
                                }
                                else if(/eid=/.test(loca)){
                                    var eid=loca.match(/eid=[0-9]+/)[0].match(/[0-9]+/)[0];
                                    tohrefurl=isweixin+"shareexppage.html?eid="+eid+"#fromuser="+md5phonenumber;
                                }
                                ////红包 联系人
                                //if(!fromuser){
                                //    $("#register").css("display","none");
                                //    $("#fromUserPhone").css("display","block");
                                //}else{
                                //    $("#finishnotic").css("display","block");
                                //}
                                //console.log("页面跳转");
                                location.href=tohrefurl;
                            }

                        },
                        error: function (d) {},
                        apiUrl: WebIM.config.apiURL
                    };
                    WebIM.utils.registerUser(options);

                }else if(data.Data==2){
                    $("#tishiinfor").html("该帐号已被注册！");
                    $("#rankErrorWord").html("该帐号已被注册！");
                }else if(data.Data==3){
                    $("#tishiinfor").html("验证码错误!");
                    $("#rankErrorWord").html("验证码错误!");
                }else if(data.Data==4){
                    $("#tishiinfor").html("用户昵称已经存在!");
                    $("#rankErrorWord").html("用户昵称已经存在!");
                }
            }
        });
    }
}
//邀请人
$("#fromUserPhoneBtn").click(function(){
    $("#fromUserPhoneError").html("PULU账号不存在");
    $("#fromUserPhoneError").css("display","none");
    $("#fromUserPhoneNote").css("display","block");
    if($("#fromphonenumber").val()){
        console.log("有内容");
        var reg=/0?(13|14|15|18)[0-9]{9}$/;
        if(!/^[0-9]+$/.test($("#fromphonenumber").val())){
            $("#fromUserPhoneError").html("手机号格式错误！");
            $("#fromUserPhoneError").css("display","block");
            $("#fromUserPhoneNote").css("display","none");
        }
        else{
            console.log("手机号正确,搜索好友");
            $.ajax({
                datatype: "json",
                type: "get",
                url: searchfriendurl+"?userId="+$.cookie("MYID")+"&nick="+$("#fromphonenumber").val(),
                success: function (data) {
                    console.log(data);
                    if(data.Data&&data.Data.length>0){
                        var searchUser=data.Data[0].userId;
                        console.log(searchUser);
                        //加好友
                        $.ajax({
                            type:"post",
                            datatype:"json",
                            url:"https://www.pulu.com/webapi/api/PuluGoodFriend/Addpulu_goodfriend",
                            data:{"userId":$.cookie("MYID"),"friendId":searchUser},
                            success:function(d){
                                if(d.Message==="不能加自己为好友"){
                                    $("#fromUserPhoneError").html("不能加自己为好友！");
                                    $("#fromUserPhoneError").css("display","block");
                                    $("#fromUserPhoneNote").css("display","none");
                                }
                                else{
                                    //关注判断
                                    if(is_weixn()){
                                        focusWX();
                                    }else{ //红包
                                        $("#finishnotic").css("display","block");
                                    }
                                }
                            }
                        });
                    }
                    else{
                        $("#fromUserPhoneError").css("display","block");
                        $("#fromUserPhoneNote").css("display","none");
                    }
                }
            })
        }
    }
    else{
        console.log("没有内容直接登录");
        $("#finishnotic").css("display","block");
    }
});
//注册完 点击红包
$("#redbox").click(function(){
    phonenumber=$("#phonenumber").val();
    var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
    $.cookie("MYID",md5phonenumber);
    var loca=location.href;
    if(/newsid=/.test(loca)){
        var newsid=loca.match(/newsid=[0-9]+/)[0].match(/[0-9]+/)[0];
        tohrefurl=isweixin+"newsdetail.html?newsid="+newsid+"#fromuser="+$.cookie("MYID");
        $.cookie("tohrefurl",tohrefurl);//用户选择类别后最终跳转地址
    }
    else if(/qid=/.test(loca)){
        var qid=loca.match(/qid=[0-9]+/)[0].match(/[0-9]+/)[0];
        tohrefurl=isweixin+"questiondetail.html?qid="+qid+"#fromuser="+$.cookie("MYID");
        $.cookie("tohrefurl",tohrefurl);//用户选择类别后最终跳转地址
    }
    else if(/eid=/.test(loca)){
        var eid=loca.match(/eid=[0-9]+/)[0].match(/[0-9]+/)[0];
        tohrefurl=isweixin+"shareexppage.html?eid="+eid+"#fromuser="+$.cookie("MYID");
        $.cookie("tohrefurl",tohrefurl);//用户选择类别后最终跳转地址
    }
    location.href=tohrefurl;
});
$('input').bind('input propertychange', function() {
    $("#tishiinfor").html("");
    $("#timplace").css("display","block");
    $("#othernote").html("");
    $("#othernote").css("display","none");
});

//物理返回操作
if( ("onhashchange" in window) && ((typeof document.documentMode==="undefined") || document.documentMode==8)) {
    //浏览器支持onhashchange事件
    window.onhashchange = hashChangeFire;
} else { // 不支持则用定时器检测的办法
    setInterval(function() {
        var thisUrl=location.href;
        if(thisUrl!=originUrl){
            originUrl=thisUrl;
            hashChangeFire();
        }
    }, 150);
}
function hashChangeFire(){
    if(!/register/.test(location.href)){
        $("#register").css("display","none");
        $(".pagedlist_item").css("display","block");
    }
}